<!-- 评估管理表格 -->
<template>
  <common-table
    :tableOptions="tableOptions"
    @onChange="handleConditionsChange"
    @onSortChange="onSortChange"
    @onFilterChange="onFilterChange"
    @rehandleSelectChange="onSelectChange"
  >
    <template #header>
      <t-space direction="vertical" style="width: 100%">
        <t-row justify="space-between">
          <t-space>
            <t-button
              theme="primary"
              :variant="selectedRowKeys.length === 0 ? 'base' : 'outline'"
              :disabled="selectedRowKeys.length === 0"
              @click="handleReminder"
              >发送提醒</t-button
            >
            <t-button
              :variant="selectedRowKeys.length === 0 ? 'base' : 'outline'"
              :disabled="selectedRowKeys.length === 0"
              theme="danger"
              @click="handleAssigned"
              >删除</t-button
            >
          </t-space>
          <t-space>
            <t-radio-group default-value="1" @change="changeRadio">
              <t-radio-button value="1">全部</t-radio-button>
              <t-radio-button value="2">与我相关</t-radio-button>
            </t-radio-group>
            <t-input @change="search" clearable style="width: 200px">
              <search-icon slot="prefix-icon"></search-icon>
            </t-input>
          </t-space>
        </t-row>
      </t-space>
    </template>
  </common-table>
</template>

<script lang="jsx">
import CommonTable from '@/components/CommonTable/index.vue';
import { SearchIcon, DeleteIcon, EditIcon, EllipsisIcon, TimeIcon, UserIcon } from 'tdesign-icons-vue';
import { DialogPlugin } from 'tdesign-vue';
import { mapState } from 'vuex';

import {
  requestQsListByPage,
  requestDeleteQsList,
  requestBatchDeleteQsDetail,
  requestSendRemind,
} from '@/service/risk-assessment/management';
import {
  tagOptions,
  dropdownOptions,
  DROPDOWN_STATUS,
  QUESTIONNAIRE_STATUS,
} from '@/constants/risk-assessment-management';
import { debounce } from '@/utils';

export default {
  name: 'RAM-Table',
  components: { CommonTable, SearchIcon },
  inject: ['reload'],
  data() {
    return {
      QUESTIONNAIRE_STATUS,
      selectedRowKeys: [],
      oprationkW: {}, // 搜索关键词、 筛选、排序
      tableOptions: {
        data: [],
        columns: [
          {
            colKey: 'row-select',
            type: 'multiple',
          },
          {
            // width: 120,
            colKey: 'name',
            title: '评估名称',
            // ellipsis: true,
            cell: (h, { row }) => <span style="color: #0052D9;">{row.name}</span>,
          },
          {
            colKey: 'status',
            title: '状态',
            sorter: true,
            // width: 120,
            // 输入框过滤配置
            cell: (h, { row }) => (
              <t-tag theme={tagOptions[row.status].theme} variant="light-outline">
                {tagOptions[row.status].name}
              </t-tag>
            ),
            filter: {
              type: 'multiple',
              resetValue: [],
              // 如果是文本域搜索，可以使用 Textarea
              // component: Textarea,
              // 按下 Enter 键时也触发确认搜索
              // confirmEvents: ['onEnter'],
              // 是否显示重置取消按钮
              showConfirmAndReset: true,
              list: [
                { label: '待填写', value: '2' },
                { label: '待审核', value: '3' },
                { label: '已完成', value: '4' },
              ],
            },
          },
          {
            colKey: 'answerName',
            title: '填写人',
            sortType: 'all',
            sorter: true,
            ellipsis: true,
            ellipsisTitle: false,
            // width: 150,
            filter: {
              type: 'multiple',
              resetValue: [],
              // 是否显示重置取消按钮
              showConfirmAndReset: true,
              list: [],
            },
            cell: (h, { row }) => (
              <div style="display: flex; align-items: center">
                <UserIcon />
                <span style="margin-left: 3px">{row.answerName}</span>
              </div>
            ),
          },
          {
            colKey: 'reviewName',
            title: '审核人',
            sortType: 'all',
            sorter: true,
            ellipsis: true,
            ellipsisTitle: false,
            // width: 150,
            // 输入框过滤配置
            filter: {
              type: 'multiple',
              resetValue: [],
              // 是否显示重置取消按钮
              showConfirmAndReset: true,
              list: [],
            },
            cell: (h, { row }) => (
              <div style="display: flex; align-items: center">
                <UserIcon />
                <span style="margin-left: 3px">{row.reviewName}</span>
              </div>
            ),
          },
          {
            colKey: 'stopDate',
            title: '截止时间',
            // width: 150,
            ellipsis: true,
            ellipsisTitle: false,
            sortType: 'all',
            sorter: true,
            cell: (h, { row }) => (
              <div
                style={
                  row.status !== QUESTIONNAIRE_STATUS.COMPLETED && new Date(row.stopDate) < Date.now() - 8.64e7
                    ? 'color: var(--td-error-color); display: flex; align-items: center'
                    : 'display: flex; align-items: center'
                }
              >
                <TimeIcon />
                <span style="margin-left: 3px">{row.stopDate?.slice(0, 11)}</span>
              </div>
            ),
          },
          {
            colKey: 'action',
            title: '操作',
            width: 200,
            // 增、删、改、查 等操作
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            cell: (h, { row }) => (
              <div class="tdesign-table-demo__table-operations">
                <t-button variant="text" onClick={() => this.handleEdit(row)}>
                  <EditIcon />
                </t-button>
                <t-button variant="text" onClick={() => this.handleDelete(row)}>
                  <DeleteIcon />
                </t-button>
                <t-dropdown
                  placement="right-top"
                  trigger="click"
                  options={dropdownOptions}
                  onClick={(e) => this.handleEllipsis(row, e)}
                >
                  <t-button variant="text" shape="square">
                    <EllipsisIcon />
                  </t-button>
                </t-dropdown>
              </div>
            ),
          },
        ],
        pagination: {
          defaultCurrent: 1,
          defaultPageSize: 10,
          total: 0,
          showJumper: true,
        },
        config: {
          rowKey: 'id',
          hover: true,
        },
      },
    };
  },
  computed: {
    ...mapState('user', ['userInfo']),
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const { defaultCurrent, defaultPageSize } = this.tableOptions.pagination;
      const pageObj = { pageNum: defaultCurrent, pageSize: defaultPageSize, ...this.oprationkW };
      requestQsListByPage(pageObj).then((res) => {
        if (!res || res.isError) return;
        const { resultQsVO, reviewNameSet, answerNameSet } = res;
        this.tableOptions.data = resultQsVO.list;
        this.tableOptions.pagination.total = resultQsVO.total;
        // 筛选数据
        this.tableOptions.columns[3].filter.list = [];
        this.tableOptions.columns[4].filter.list = [];
        for (let i = 0; i < answerNameSet?.length; i++) {
          if (!answerNameSet[i]?.rsUserId) {
            break;
          }
          this.tableOptions.columns[3].filter.list.push({
            label: answerNameSet[i]?.rsUserName,
            value: answerNameSet[i]?.rsUserId,
          });
        }
        for (let i = 0; i < reviewNameSet?.length; i++) {
          if (!reviewNameSet[i]?.rsUserId) {
            break;
          }
          this.tableOptions.columns[4].filter.list.push({
            label: reviewNameSet[i]?.rsUserName,
            value: reviewNameSet[i]?.rsUserId,
          });
        }
      });
    },
    handleEdit(row) {
      this.$router.push({ path: '/risk-assessment/management/answer', query: { id: row.id } });
    },
    handleDelete(row) {
      const dialog = DialogPlugin.confirm({
        theme: 'warning',
        header: '警告',
        body: '再次确认是否删除问卷？',
        onConfirm: () => {
          requestDeleteQsList(row.id).then((res) => {
            if (!res || res.isError) return;
            this.$message.success('删除问卷成功');
            if (this.tableOptions.data.length === 1 && this.tableOptions.pagination.defaultCurrent > 1) {
              this.tableOptions.pagination.defaultCurrent -= 1;
            }
            this.fetchData();
            this.$bus.$emit('updateDashboard');
            dialog.destroy();
          });
        },
      });
    },
    handleEllipsis(row, e) {
      if (e.value === DROPDOWN_STATUS.EDIT) {
        this.$router.push({ path: '/risk-assessment/management/start', query: { id: row.id } });
      }
      if (e.value === DROPDOWN_STATUS.REMIND) {
        this.sendRemind([row.id]);
      }
    },
    handleConditionsChange(info) {
      if (info?.pagination) {
        this.tableOptions.pagination.defaultCurrent = info?.pagination?.current;
        this.tableOptions.pagination.defaultPageSize = info?.pagination?.pageSize;
        this.fetchData();
      }
    },
    search: debounce(function fn(val) {
      this.oprationkW.inputContent = val;
      this.tableOptions.pagination.defaultCurrent = 1;
      // 没有搜索参数,接口要求也不传key
      if (!val) delete this.oprationkW.inputContent;
      this.fetchData();
    }, 1000),
    onSortChange(sort) {
      this.oprationkW.orderColum = sort?.sortBy;
      if (sort?.descending) {
        this.oprationkW.orderType = 'desc';
      } else {
        this.oprationkW.orderType = 'asc';
      }
      // 不排序的时候 不传参数
      if (!sort) {
        delete this.oprationkW.orderColum;
        delete this.oprationkW.orderType;
      }
      this.fetchData();
    },
    onFilterChange(filters) {
      this.tableOptions.pagination.defaultCurrent = 1;
      if (filters?.status && filters?.status.length > 0) {
        this.oprationkW.statusList = filters?.status;
      } else {
        delete this.oprationkW.statusList;
      }
      if (filters?.answerName && filters?.answerName.length > 0) {
        this.oprationkW.answerIdList = filters?.answerName;
      } else {
        delete this.oprationkW.answerIdList;
      }
      if (filters?.reviewName && filters?.reviewName.length > 0) {
        this.oprationkW.reviewIdList = filters?.reviewName;
      } else {
        delete this.oprationkW.reviewIdList;
      }
      this.fetchData();
    },
    handleReminder() {
      this.sendRemind(this.selectedRowKeys);
    },
    sendRemind(ids) {
      requestSendRemind(ids).then((res) => {
        if (!res || res.isError) return;
        this.$message.success(res.message);
        this.reload();
      });
    },
    handleAssigned() {
      const dialog = DialogPlugin.confirm({
        theme: 'warning',
        header: '提示',
        body: '再次确认是否删除问卷？',
        onConfirm: () => {
          requestBatchDeleteQsDetail(this.selectedRowKeys).then((res) => {
            if (!res || res.isError) return;
            this.$message.success('删除问卷成功');
            this.selectedRowKeys = [];
            this.reload();
            this.$bus.$emit('updateDashboard');
            dialog.destroy();
          });
        },
      });
    },
    onSelectChange(val) {
      this.selectedRowKeys = val;
    },
    // 单选框切换
    changeRadio(val) {
      this.tableOptions.pagination.defaultCurrent = 1;
      if (val === '2') this.oprationkW = { ...this.oprationkW, myselfId: this.userInfo.id };
      else this.$delete(this.oprationkW, 'myselfId');
      this.fetchData();
    },
  },
};
</script>
